package ldh.text.service;

import ldh.text.util.FileSizeUtil;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;

public class FileDataService implements DataService<ByteBuffer> {

    private File file;
    private long fileSize;

    public FileDataService() {}

    public FileDataService(File file) throws IOException {
        this.file = file;
        fileSize = FileSizeUtil.getFileSize(file.toPath());
    }

    public void setFile(File file) {
        this.file = file;
    }

    public File getFile() {
        return file;
    }

    @Override
    public long dataSize() {
        if (file == null) {
            throw new RuntimeException("file 为空");
        }
        return fileSize;
    }

    @Override
    public ByteBuffer loadData(long position, int size) throws IOException {
        try(RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            FileChannel fileChannel = randomAccessFile.getChannel();) {
            fileSize = fileChannel.size();
            ByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

            byte[] data = new byte[size];
            byteBuffer.position((int)position);
            byteBuffer.get(data, 0, size);
            return ByteBuffer.wrap(data);
        }
    }

    @Override
    public void saveData(String file, byte[] data, int startPosition, int endPosition) {

    }

    @Override
    public void saveData(File file, byte[] data) throws IOException {
        if (file.exists()) {
            Files.write(file.toPath(), data, StandardOpenOption.WRITE);
        } else {
            Files.write(file.toPath(), data);
        }
    }
}
